package by.ins.app;

import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import by.ins.app.commands.AppCommnandProvider;
import by.ins.life.evolution.ILifeEvoluter;
import by.yativem.commons.task.TasksEngine;


public final class AppContext implements ApplicationContextAware {
	@Autowired
	protected static ApplicationContext context;
	
/*	static{
		context = new ClassPathXmlApplicationContext("application-context.xml");
	}
*/	
	public static ApplicationContext getSpringContext(){
	//	ApplicationContext i;
		return context;
	}
	
	public static Object getBean(String name){
		Object result = getSpringContext().getBean(name);
		if(result == null) throw new IllegalArgumentException( new StringBuilder( "Bean with taskName ").append(name).append("was not found").toString() );
		return result;
	}
	
	public static TasksEngine getTaskEngine(){		
		return (TasksEngine)  getApp().getTasksEngine();
	}
	
	public static AppCommnandProvider getAppCommnandProvider(){
		return (AppCommnandProvider) getSpringContext().getBean("appCommnandProvider");
	}
	
	public static App getApp(){
		return (App) getSpringContext().getBean("app");
	}
	
/*	public static AppCommnandProvider getAppCommandProvider(){
		App app = getApp();
		return app.getAppCommnandProvider();
	}
	*/
/*	
	@SuppressWarnings("unchecked")
	public static Map<String, ILifeEvoluter> getDefnedLifeEvolutor(){
		return (Map<String, ILifeEvoluter>) getSpringContext().getBean("lifes");
	}
*/	
	
	public static List<ILifeEvoluter> getDefinedLifeEvolutor(){
		return getSpringContext().getBean("lifeEvolutors",  List.class );
	}
	
	public static ILifeEvoluter getDefiendLifeEvoluter(String name){
		
		return AppHelper.getLiveEvoluter(name);
	/*	Map<String, ILifeEvoluter> map = 	(Map<String, ILifeEvoluter>) getSpringContext().getBean("lifes");
		ILifeEvoluter result = null;
		for(ILifeEvoluter evoluter : map.values()){
			if(name.equals(evoluter.getName())){
				result = evoluter;
				break;
			}
		}
		 return result;
		 */
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		
		AppContext.context = applicationContext;
		
	}
	

	
/*	public static IEvoluter bind(Object object){
		//XMLDecoder decoder =  new XMLDecoder(null);
		//decoder.
		File file = new File("d:\\context.xml");
		XMLEncoder encoder = null ;
		try {
			encoder= new XMLEncoder(new FileOutputStream(file));
			encoder.writeObject(object);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			encoder.close();
		}
		
		return null;
	}
	*/

}
